// router/index.js

import modules from './modules';
import Vue from 'vue';
import Router from '@/components/uni-simple-router/index.js';
import { syncLoginH5, getMenu } from '@/api/index';
import store from '@/utils/store';
import utils from '@/utils/util.js'; //获取工具类
import { getJzSelect, getZhiSelect, jzjfxmSelect, zjjfxmSelect } from '@/api/info.js';

Vue.use(Router);
const router = new Router({
	routes: [ ...modules ] //路由表
});

// 路由白名单
const whiteList = [ '/pages/global/error/404', '/pages/global/error/loginFalse', '/pages/global/error/permission' ];

router.beforeEach((to, from, next) => {
	next();
	if (whiteList.indexOf(to.path) !== -1) {
		next();
	}
	if (!sessionStorage.getItem('token')) {
		let keyMap = utils.getUrlKey('token');
		//let keyMap = 'd438b483af4641d6988c9883076584c2bbc03ed9'
		if (keyMap != null && keyMap != undefined) {
			let params = { token: keyMap }; //小慧环境
			syncLoginH5(params).then((data) => {
				console.log(data, '请求小慧');
				if (data.success === true) {
					sessionStorage.setItem('token', data.data.JSESSIONID);
					sessionStorage.setItem('userId', data.data.id);
					store.commit('bingLogin', data);

					//获取权限
					let permissions = [];
					getMenu().then((result) => {
						if (result.success) {
							let data = result.data;
							for (let i = 0; i < data.length; i++) {
								let permission = data[i].value;
								if (permission && permission.length !== 0) {
									permissions.push(permission);
								}
							}
						} else {
							console.log(result.message);
						}

						sessionStorage.setItem('permissions', permissions);
						store.commit('bingPermission', permissions);
						next();
					});
				} else if (data.success === false) {
					next({
						path: '/pages/global/error/loginFalse',
						params: {
							mess: data.mess
						},
						NAVTYPE: 'replace'
					});
				} else {
					next({
						path: '/pages/global/error/404',
						NAVTYPE: 'replace'
					});
				}
			});
		} else {
			next({
				path: '/pages/global/error/loginFalse',
				params: {
					mess: '请通过小慧进入'
				},
				NAVTYPE: 'replace'
			});
		}
	} else {
		next();
	}
});
// 全局路由后置守卫
router.afterEach((to, from) => {});
export default router;
